/* 
 * @name login.js
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 * @version 1.0
 */

var Login = {
    container:null,
    centered:null,
    formLogin:null,

    init:function () {
        var self = this;

        self.container = $('#container');
        self.formLogin = $('#form-login');

        var doc = $('html').addClass('js-login');

        $("#login, #pass").keypress(function(e) {
            var code = (e.keyCode ? e.keyCode : e.which);
            if(code == 13) { //Enter keycode
                self.submitForm();
            }
        });

        $('#login-btn').click(function () {
            self.submitForm();
        });

        // Register and first call
        $(window).bind('normalized-resize', self.handleLoginResize);
        self.handleLoginResize();
        // Initial vertical adjust
        self.centerForm(false);

        // What about a notification?
        jLib.notification('Login', 'Login with your username and password',false);
    },

    /*
     * AJAX login
     * This function will handle the login process through AJAX
     */
    submitForm:function () {
        var self = this;
        // Values
        var login = $.trim($('#login').val()), pass = $.trim($('#pass').val());

        // Check inputs
        if (login.length === 0) {
            // Display message
            self.displayError('Please fill in your username');
            return false;
        }
        else if (pass.length === 0) {
            // Remove empty login message if displayed
            self.formLogin.clearMessages('Please fill in your login');

            // Display message
            self.displayError('Please fill in your password');
            return false;
        }
        else {
            // Remove previous messages
            self.formLogin.clearMessages();

            // Show progress
            self.displayLoading('Checking credentials...','orange-gradient');

            var query = self.formLogin.serialize();
            var url = $('#login-url').val();
            /* Send the data to the server and handle the server response */
            $.ajax({
                url: url,
                data: query,
                dataType: 'json',
                type: 'POST',
                success:function(response) {
                    var txt = '';
                    if (typeof response.mesg == 'object') {
                        for (megTxt in response.mesg) {
                            txt += response.mesg[megTxt] + '<br />';
                        }
                    }
                    else {
                        txt = response.mesg
                    }
                    /* When everything went on smoothly on the server redirect the user to the appropriate page.*/
                    if (response.code === 0) {
                        self.formLogin.clearMessages();
                        // Show progress
                        self.displayLoading('Login Success!!! Redirecting...','green-gradient');
                        //alert($('#after-login-url').val());
                        window.location = $('#after-login-url').val();
                    }
                    /* When there are Errors */
                    else if (response.code === 1) {
                        self.formLogin.clearMessages();
                        self.displayError(txt);
                    }
                },
                error: function(xhr) {
                    console.log(xhr.responseText);
                    self.formLogin.clearMessages();
                    self.displayError('Error while contacting server, please try again');
                }
            });

            /*// Simulate server-side check
            setTimeout(function () {
                //document.location.href = 'index.html'
            }, 2000);*/
        }
    },


    validate:function () {
        var self = this;


    },


    // Handle resizing (mostly for debugging)
    handleLoginResize:function () {
        var self = this;

        //var container = $('#container');

        // Detect mode
        Login.centered = (Login.container.css('position') === 'absolute');

        // Set min-height for mobile layout
        if (!Login.centered) {
            Login.container.css('margin-top', '');
        }
        else {
            if (parseInt(Login.container.css('margin-top'), 10) === 0) {
                Login.centerForm(false);
            }
        }
    },

    /*
     * Center function
     * @param boolean animate whether or not to animate the position change
     * @param string|element|array any jQuery selector, DOM element or set of DOM elements which should be ignored
     * @return void
     */
    centerForm:function centerForm(animate, ignore) {
        var self = this;
        // If layout is centered
        if (self.centered) {
            var siblings = self.formLogin.siblings(), finalSize = self.formLogin.outerHeight();

            // Ignored elements
            if (ignore) {
                siblings = siblings.not(ignore);
            }
            // Get other elements height
            siblings.each(function (i) {
                finalSize += $(this).outerHeight(true);
            });
            // Setup
            self.container[animate ? 'animate' : 'css']({ marginTop:-Math.round(finalSize / 2) + 'px' });
        }
    },

    /**
     * Function to display error messages
     * @param string message the error to display
     */
    displayError:function (message) {
        var self = this;
        // Show message
        var message = self.formLogin.message(message, {
            append:false,
            arrow:'bottom',
            classes:['red-gradient'],
            animate:false  // We'll do animation later, we need to know the message height first
        });

        // Vertical centering (where we need the message height)
        self.centerForm(true, 'fast');

        // Watch for closing and show with effect
        message.bind('endfade',
            function (event) {
                // This will be called once the message has faded away and is removed
                self.centerForm(true, message.get(0));
            }).hide().slideDown('fast');
    },

    /**
     * Function to display loading messages
     * @param string message the message to display
     */
    displayLoading:function (message,color) {
        var self = this;
        // Show message
        var message = self.formLogin.message('<strong>' + message + '</strong>', {
            append:false,
            arrow:'bottom',
            classes:[color, 'align-center'],
            stripes:true,
            darkStripes:false,
            closable:false,
            animate:false // We'll do animation later, we need to know the message height first
        });

        // Vertical centering (where we need the message height)
        self.centerForm(true, 'fast');

        // Watch for closing and show with effect
        message.bind('endfade',
            function (event) {
                // This will be called once the message has faded away and is removed
                self.centerForm(true, message.get(0));
            }).hide().slideDown('fast');
    },


    submitFormXX:function () {
        /* Validation Status of the Login Form. It checks whether the data input by the user are correct or not. */
        var validationStatus = $('#login-form').validationEngine({returnIsValid:true});

        /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
        if (validationStatus) {
            /* Preparation of the data to send to the server to be processed. Here we retrieve the data from the login form. */
            var query = $('#login-form').serialize();
            login.ssUrl = $('#login-url').attr('data-url');
            /* Send the data to the server and handle the server response */
            $.post(login.ssUrl, query, function (response) {
                var txt = '';

                if (typeof response.mesg == 'object') {
                    for (megTxt in response.mesg) {
                        txt += response.mesg[megTxt] + '<br />';
                    }
                }
                else {
                    txt = response.mesg
                }
                /* When everything went on smoothly on the server redirect the user to the appropriate page.*/
                if (response.code === 0) {
                    $.validationEngine.buildPrompt(".login-prompt", "Login Success!!! Redirecting...", "pass");
                    window.location = $('#action_after_login-url').attr('data-url');
                }
                /* When there are Errors */
                else if (response.code === 1) {
                    $.validationEngine.buildPrompt(".login-prompt", txt, "error");
                }
            }, 'json');
        }
    }
}
    ;

/* when the page is loaded */
$(document).ready(function () {
    Login.init();
});